/*
 * Created on Sun Oct 01 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';

import type { IFileUploadStrategy } from './IFileUploadStrategy';
import type {
  UploadFileParam,
  UploadFileResult,
} from '../../../types';
import  { File } from '../../../db/models';
import config from '../../../config';
import fse from 'fs-extra';
import path from 'path';
import uuidv4 from 'uuid/v4'
import mime from 'mime';
import URI from 'urijs';

export default class LocalFileSaveStrategy implements IFileUploadStrategy {
  async upload(param: UploadFileParam): Promise<UploadFileResult> {
    //创建目录
    let ext = mime.getExtension(param.mimeType);
    let fileName = uuidv4();
    if (ext) {
      fileName = fileName + '.' + ext;
    }

    let destPath = path.join(config.path.uploadDir, fileName);
    //移动
    await fse.move(param.path, destPath, { overwrite: true });

    var uri = new URI({
      protocol: "file", 
      hostname: "localhost",
      path: destPath,
    });

    let doc = await File.create({
      uri: uri.toString(),
      mimeType: param.mimeType,
      md5: param.md5,
    });

    return {
      fid: doc.id,
      uri: doc.uri,
      mimeType: doc.mimeType,
      md5: doc.md5,
    }
  }
}